import db from '~~/DB';
import { defineResponseResolver } from '~~/mocks/define';
import {} from 'msw';
import { validateMenu } from '~~/mocks/middleware/menu';

export default validateMenu('system-user', async (req, res, ctx) => {
  const name = req.url.searchParams.get('name') || '';
  const status = req.url.searchParams.get('status');
  const page = Number(req.url.searchParams.get('page') || 1);
  const pageSize = Number(req.url.searchParams.get('pageSize') || 10);
  // console.log(name, page, pageSize);

  // if (page >= 5) {
  //   return res(ctx.status(400), ctx.json({ message: 'page >= 5 ' }));
  // }

  const table = db.users;

  //  table.where('status')

  let collection = table.toCollection();
  // const query: Record<string, any> = {};
  // collection = collection.w
  name &&
    (collection = collection.filter((value) => value.name.includes(name)));

  status &&
    (collection = collection.filter(
      (value) => value.status === Number(status),
    ));

  const total = await collection.count();
  const users = await collection
    .offset(pageSize * (page - 1))
    .limit(pageSize)
    .toArray();

  // return res(
  //   ctx.json({
  //     list: users.map((v) => ({ ...v, password: undefined })),
  //     total,
  //   }),
  // );

  // if (Object.keys(query).length > 0) {
  //   const total = await db.users.where(query).count();
  //   const users = await db.users
  //     .where(query)
  //     .offset(pageSize * (page - 1))
  //     .limit(pageSize)
  //     .toArray();

  //   return res(
  //     ctx.json({
  //       list: users.map((v) => ({ ...v, password: undefined })),
  //       total,
  //     }),
  //   );
  // }
  // const total = await db.users.count();
  // const users = await db.users
  //   .offset(pageSize * (page - 1))
  //   .limit(pageSize)
  //   .toArray();

  return res(
    ctx.json({
      list: users.map((v) => ({ ...v, password: undefined })),
      total,
    }),
  );
});
